<?php
/**
 * 员工管理模型
 */

namespace app\common\model;

use think\db\Query;
use think\model\concern\SoftDelete;

class Staff extends Model
{
    use SoftDelete;
    public $softDelete = true;
    protected $name = 'staff';
    protected $autoWriteTimestamp = true;

    //可搜索字段
    protected $searchField = ['name', 'mobile', 'id_card',];
    protected $whereField = ['id','department_id','hired_date','full_date','full_salary_date','birthday_month','position_id'];

    //性别获取器
    public function getSexTextAttr($value, $data)
    {
        return self::BOOLEAN_TEXT[$data['sex']];
    }//是否部门领导获取器

    public function getIsLeaderTextAttr($value, $data)
    {
        return self::BOOLEAN_TEXT[$data['is_leader']];
    }//是否启用获取器

    public function getStatusTextAttr($value, $data)
    {
        return self::BOOLEAN_TEXT[$data['status']];
    }

    //关联部门
    public function department()
    {
        return $this->belongsTo(Department::class);
    }

    //
    public function insure()
    {
        return $this->belongsTo(Insure::class);
    }
    public function position()
    {
        return $this->belongsTo(Position::class);
    }

    /**
     * 查询处理
     * @var Query $query
     * @var array $param
     */
    public function scopeWhere($query, $param)
    {
        //关键词like搜索
        $keywords = $param['_keywords'] ?? '';
        if (!empty($keywords) && count($this->searchField) > 0) {
            $this->searchField = implode('|', $this->searchField);
            $query->where($this->searchField, 'like', '%' . $keywords . '%');
        }

        //字段条件查询
        if (count($this->whereField) > 0 && count($param) > 0) {
            foreach ($param as $key => $value) {
                if (!empty($value) && in_array($key, $this->whereField)) {
                    if ($key === 'hired_date' || $key === 'full_salary_date'|| $key === 'full_date'){
                        $start_date = date('Y-m-d', mktime(00, 00, 00, date('m', strtotime($value)), 01));
                        $end_date = date('Y-m-d', mktime(23, 59, 59, date('m', strtotime($value))+1, 00));
                        $query->whereBetween($key,[$start_date,$end_date]);
                    }else{
                        $query->where($key, $value);
                    }
                }
            }
        }

        //排序
        $order = $param['_order'] ?? '';
        $by    = $param['_by'] ?? '';
        $query->order($order ?: '', $by ?: '');
    }

}
